#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "posix_qextserialport.h"
#include "utils.h"
#include<QStringList>
#include<serialthread.h>
#include<QDateTime>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
    QSerialPort serial;
    serial.setPort(info);
    if(serial.open(QIODevice::ReadWrite)){
        showMsg(info.portName(),3);
        serial.close();
    }
    }
    flag = 0;
    connect(ui->sendMsgBtn,SIGNAL(clicked()),this,SLOT(on_pushButton_clicked()));
    connect(ui->stopButton,SIGNAL(clicked()),this,SLOT(on_stopBUtton_clicked()));
    connect(ui->clearButton,SIGNAL(clicked()),this,SLOT(on_clearButton_clicked()));
    m_Serial_Thread_CardReader =new SerialThread();
    m_Serial_Thread_CardReader->start();
    connect(m_Serial_Thread_CardReader,SIGNAL(m_GPRS_Done_CardReader(QByteArray)),this,SLOT(read_GPRS_Com_CardReader(QByteArray)));
    connect(m_Serial_Thread_CardReader,SIGNAL(m_GPRS_Disconnect_CardReader()),this,SLOT(disconnect_CardReader()));

    m_Serial_Thread_CardEmulation = new SerialThread2();
    m_Serial_Thread_CardEmulation->start();
    connect(m_Serial_Thread_CardEmulation,SIGNAL(m_GPRS_Done_CardEmulation(QByteArray)),this,SLOT(read_GPRS_Com_CardEmulation(QByteArray)));
    connect(m_Serial_Thread_CardEmulation,SIGNAL(m_GPRS_Disconnect_CardEmulation()),this,SLOT(disconnect_CardEmulation()));
}

void MainWindow::read_GPRS_Com_CardReader(QByteArray temp){
    Utils ut;
    QString strRead;
    QString strWrite;
    int result=1;
    int beginIndex=0,endIndex=0;
    QStringList sl;
    QStringList slTmp = ut.byteArraytoHexString(temp);
    for(int i = 0;i<slTmp.size();i++){
        if(slTmp[i]=="24"){
            beginIndex = i;
            break;
        }
    }
    for(int i=slTmp.size()-1;i>=0;i--){
        if(slTmp[i]=="23"){
            endIndex = i;
            break;
        }
    }
    for(int i =0;i<(endIndex-beginIndex+1);i++){
        sl <<slTmp[beginIndex+i];
    }
    if(sl.size()>4 && sl[0]=="24"){
    result = oddEvenVerify(temp);
    }
    for(int i = 0;i<sl.size();i++){
        strRead.append(sl[i]).append(' ');
    }
    if(result == 0 && sl[2]=="00"){    //**verify ok  , request
        if("d2"==sl[4]){  // APDU
    QString strResponse = "2424010100002323";
    showMsg(strRead,0);
    if(sl[3]=="01"){   //RID = "01"
        sl[3]="00";
        if(sl[sl.size()-3]=="00"){
            sl[sl.size()-3] = "01";
        }else if(sl[sl.size()-3]=="01"){
            sl[sl.size()-3] ="00";
        }
    }
    for(int i = 0;i<sl.size();i++){
        strWrite.append(sl[i]);
    }
    QByteArray writeByteArray = ut.hexStringtoByteArray(strWrite);
    QByteArray responseByteArray = ut.hexStringtoByteArray(strResponse);
    m_Serial_Thread_CardEmulation->m_GPRS_Com->write(writeByteArray);
    m_Serial_Thread_CardReader->m_GPRS_Com->write(responseByteArray);
        }else if("d1"==sl[4]){ //UID
            QString tmp;
            tmp.append("RID is ").append(sl[3]).append(" --- UID is ").append(sl[6]).append(sl[7]).append(sl[8]).append(sl[9]);
             showMsg(tmp,0);
             QString strResponse = "2424010100002323";
             QByteArray responseByteArray = ut.hexStringtoByteArray(strResponse);
             m_Serial_Thread_CardReader->m_GPRS_Com->write(responseByteArray);
        }else{
           QString strResponse = "2424010100002323";
           QByteArray responseByteArray = ut.hexStringtoByteArray(strResponse);
           m_Serial_Thread_CardReader->m_GPRS_Com->write(responseByteArray);
        }
    }else if(0==result && "01"==sl[2]){ //**verify ok, response
        showMsg(strRead,0);
    }
}

void MainWindow::read_GPRS_Com_CardEmulation(QByteArray temp){
    Utils ut;
    QString strRead;
    QString strWrite;
    int result=1 ;
    int beginIndex=0,endIndex=0;
    QStringList sl;
    QStringList slTmp = ut.byteArraytoHexString(temp);
    for(int i = 0;i<slTmp.size();i++){
        if(slTmp[i]=="24"){
            beginIndex = i;
            break;
        }
    }
    for(int i=slTmp.size()-1;i>=0;i--){
        if(slTmp[i]=="23"){
            endIndex = i;
            break;
        }     
    }
    for(int i =0;i<(endIndex-beginIndex+1);i++){
        sl<<slTmp[beginIndex+i];
       // showMsg(slTmp[beginIndex+i],0);
    }

    for(int i = 0;i<sl.size();i++){
        strRead.append(sl[i]);
    }

    if(sl.size()>4&&sl[0]=="24"){
    result = oddEvenVerify(ut.hexStringtoByteArray(strRead));
    }

    if(result == 0 && sl[2]=="00"){    //**verify ok  , request
             if("d2"==sl[4]){  // APDU
            QString strResponse = "2424010000012323";
        showMsg(strRead,1);
        if(sl[3]=="00"){   //RID = "00"
            sl[3]="01";
            if(sl[sl.size()-3]=="00"){
                sl[sl.size()-3] = "01";
            }else if(sl[sl.size()-3]=="01"){
                sl[sl.size()-3] ="00";
            }
        }
        for(int i = 0;i<sl.size();i++){
            strWrite.append(sl[i]);
        }
        QByteArray writeByteArray = ut.hexStringtoByteArray(strWrite);
        QByteArray responseByteArray = ut.hexStringtoByteArray(strResponse);
        m_Serial_Thread_CardReader->m_GPRS_Com->write(writeByteArray);
        m_Serial_Thread_CardEmulation->m_GPRS_Com->write(responseByteArray);
        //sleep(100);
       // QString tmptmp = "24240001D23B6F37840E4E432E65436172642E4444463031A5259F0801029F0C1E6E6577636170656300008B0300127000005713510000000000000000A6969000012323";
//        QByteArray tmpArray = ut.hexStringtoByteArray(tmptmp);
//        m_Serial_Thread_CardEmulation->m_GPRS_Com->write(tmpArray);
             }else{
                    QString strResponse = "2424010000012323";
                    QByteArray responseByteArray = ut.hexStringtoByteArray(strResponse);
                    m_Serial_Thread_CardEmulation->m_GPRS_Com->write(responseByteArray);
             }
        }else if(0==result && "01"==sl[2]){ //**verify ok, response
            showMsg(strRead,1);
        }
   }

void MainWindow::on_pushButton_clicked(){
    Utils ut;
    QString reader = "24240001d300002323";
    QString card =   "24240000d300012323";
    QByteArray readerByte = ut.hexStringtoByteArray(reader);
    QByteArray cardByte = ut.hexStringtoByteArray(card);
    m_Serial_Thread_CardReader->m_GPRS_Com->write(readerByte);
    m_Serial_Thread_CardEmulation->m_GPRS_Com->write(cardByte);
}

void MainWindow::on_stopBUtton_clicked(){
    Utils ut;
    QString reader = "24240001d400012323";
    QString card =   "24240000d400002323";
    QByteArray readerByte = ut.hexStringtoByteArray(reader);
    QByteArray cardByte = ut.hexStringtoByteArray(card);
    m_Serial_Thread_CardReader->m_GPRS_Com->write(readerByte);
    m_Serial_Thread_CardEmulation->m_GPRS_Com->write(cardByte);
}

void MainWindow::on_clearButton_clicked(){
    ui->textBrowser->setPlainText("");
}

void MainWindow::showMsg(QString str,int type){
    Utils ut;
    if(0==type){
     QColor clrR(0,255,0);
     ut.stringToHtmlFilter(str);
     ut.stringToHtml(str,clrR);
    }else if(1==type){
        QColor clrR(0,0,255);
        ut.stringToHtmlFilter(str);
        ut.stringToHtml(str,clrR);
    }else if(2==type){
         QColor clrR(255,0,0);
         ut.stringToHtmlFilter(str);
         ut.stringToHtml(str,clrR);
    }else if(3==type){
         QColor clrR(72,72,72);
         ut.stringToHtmlFilter(str);
         ut.stringToHtml(str,clrR);
    }

    ui->textBrowser->insertHtml(str);
    ui->textBrowser->insertPlainText("\n");
}

void MainWindow::disconnect_CardReader(){
    showMsg("CardReader disconnected !",2);
}

void MainWindow::disconnect_CardEmulation(){
   showMsg("CardEmulation disconnected !",2);
}

int MainWindow::oddEvenVerify(QByteArray temp){
    Utils ut;
    int odd_even = 0;
    QByteArray dataByteArray;
    if(temp.size()>4){
    for(int i = 2;i<temp.size()-2;i++){
        dataByteArray[i-2] = temp[i];
    }
    }
    int numOf1 = ut.verify(dataByteArray);
    //QString numOf1Str = QString::number(numOf1,10);
    if(numOf1%2==1){
        odd_even = 1;
        showMsg("Verify Fail !!",2);
    }else{
        //showMsg("Verify OK !!",2);
    }
    return odd_even;
}

void MainWindow::sleep(int msec)//自定义Qt延时函数,单位毫秒
{
    QDateTime last = QDateTime::currentDateTime();
    QDateTime now;
    while (1)
    {
        now = QDateTime::currentDateTime();
        if (last.msecsTo(now) >= msec)
        {
            break;
        }
    }
}


MainWindow::~MainWindow()
{
    delete ui;
}
